/*
 * Copyright (C) 2014  Forklabs Daniel Léonard
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package ca.forklabs.trello.client;

import java.net.URL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import ca.forklabs.baselib.io.StreamUtil;
import ca.forklabs.trello.client.model.Board;
import ca.forklabs.trello.client.model.Card;

import java.io.IOException;

public class TrelloClient {

   public static final String TRELLO_API_BASE_URL = "https://api.trello.com/";

   public static final String TRELLO_API_VERSION = "1/";

   private String key;

   public TrelloClient() {

      }

   public TrelloClient(String key) {
      this.setKey(key);

      }

   public TrelloClient setKey(String key) {
      this.key = key;
      return this;
      }

   public String getKey() {
      return this.key;
      }

   protected String connect(String resource) throws IOException {
      String url = TRELLO_API_BASE_URL + TRELLO_API_VERSION + resource + "&key=" + this.getKey();
      String json = StreamUtil.readAllText(new URL(url));
      return json;
      }


   public Card[] cards(Board board) throws IOException, JSONException {
      String resource = board.toResource() + "/cards" + "?" + "fields=id,name,desc,due";

      String json = this.connect(resource);
      JSONArray array = new JSONArray(json);
//System.out.println(array.toString(3));

      int size = array.length();
      Card[] cards = new Card[size];
      for (int i = 0, len = size; i < len; i++) {
         Card card = new Card();

         JSONObject jo = (JSONObject) array.get(i);

         card.id = jo.getString("id");
         card.name = jo.getString("name");
         card.desc = jo.getString("desc");

         Object due = jo.get("due");
         if (JSONObject.NULL != due) {
            card.due = (String) due;
            }

         cards[i] = card;
         }

      return cards;
      }

   }
